package com.example.PriceCompare;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

public class SearchScreen extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
    private Button ChangeButton;
    private Button SearchButton;
    private RadioButton currLocation;
    private RadioButton changeLocation;
    private double CurLat, CurLong;
    private Location location;
    private TextView CurLocation, StoreText, SearchText, DistanceText;
    public DatabaseAdapter mDbHelper;
    private double tempDist;
    
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.searchscreen);
/*        String url[] = new String[500];
        String name[] = new String[500];
        String price[] = new String[500];
        String address[] = new String[500];
        String number[] = new String[500];

        try{
        String strFile= "/res/raw/items.csv";
        BufferedReader br = new BufferedReader( new FileReader(strFile));
        String strLine = "";
        StringTokenizer st = null;
        int lineNumber = 0, tokenNumber = 0;

        //read comma separated file line by line
        while( (strLine = br.readLine()) != null)
        {
        lineNumber++;

        //break comma separated line using ","
        st = new StringTokenizer(strLine, ",");

        while(st.hasMoreTokens())
        {
        //display csv values
        tokenNumber++;
        if(tokenNumber ==1 ){
        url[lineNumber]= st.nextToken();
        }else if(tokenNumber == 2){
        name[lineNumber] = st.nextToken();
        }else if(tokenNumber == 3){
        price[lineNumber] = st.nextToken();
        }else if(tokenNumber == 4){
        address[lineNumber] = st.nextToken();
        }else if(tokenNumber == 5){
        number[lineNumber] = st.nextToken();
        }
        }
        //reset token number
        tokenNumber = 0;

        }
        }catch(Exception e){
        	//System.out.println(e.getMessage());
        }*/

        //comment the display and on click listener to run any other xml except main
/*        mDbHelper = new DatabaseAdapter(this);
        mDbHelper.open();
        for(int i=0;i<url.length;i++)
        {
//        	if(price[i]!=null)
        	{
        		Log.i("imp", " "+i);
        		mDbHelper.createItem("asd","ads",500,"asd",0);		
        	}
        
        }
//		mDbHelper.createItem("Arambol beach","rt",4000,"0",0);
//		mDbHelper.createItem("Vasco","rgfs",5000,"0",0);
		mDbHelper.close();*/
        
        
        
        LocationManager mlocManager =(LocationManager)getSystemService(Context.LOCATION_SERVICE);
		MyLocationListen mlocListener = new MyLocationListen();
		location = mlocManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);		
		mlocManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0, mlocListener);
//		if(location!=null)
//		{
		CurLat = location.getLatitude();
		CurLong=location.getLongitude();
//		}
/*		else
		{
			Toast.makeText(this, "Cant find location", Toast.LENGTH_LONG).show();
		}*/
//		Toast.makeText(this, "LAT="+CurLat+" LONG="+CurLong, Toast.LENGTH_LONG).show();
		Log.d("test","here"+ " LAT="+CurLat+" LONG="+CurLong);
		CurLocation = (TextView)findViewById(R.id.LocationText);
		StoreText = (TextView)findViewById(R.id.StoreText);
		SearchText = (TextView)findViewById(R.id.SearchText);
		DistanceText = (TextView)findViewById(R.id.DistanceText);
		CurLocation.setText(getAddress(CurLat,CurLong));
		Log.d("test","===="+getAddress(CurLat,CurLong));
		ChangeButton = (Button)findViewById(R.id.ChangeButton);
        ChangeButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(SearchScreen.this,ChangeStore.class); 
				startActivityForResult(intent, 0);
				// TODO Auto-generated method stub
				
			}
		});
        
        SearchButton = (Button)findViewById(R.id.SearchButton);
        SearchButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(SearchScreen.this,SearchResult.class);
				Bundle bundle =new Bundle();
				bundle.putDouble("lat", CurLat);
				bundle.putDouble("long", CurLong);
				bundle.putString("searchkey",SearchText.getText().toString());
			
				if(DistanceText.getText().toString().length()<=0)
				{
					bundle.putDouble("distance",20.0);
				}
				else{
					tempDist=Double.parseDouble(DistanceText.getText().toString());
					bundle.putDouble("distance",tempDist);	
				}
				
				intent.putExtras(bundle);
				startActivity(intent);
				// TODO Auto-generated method stub
				
			}
		});
        
        currLocation =(RadioButton)findViewById(R.id.ButtonCurrentLocation);
        changeLocation = (RadioButton) findViewById(R.id.ButtonSelectLocation);
        currLocation.setChecked(true);
        changeLocation.setOnClickListener(this);
        
    }
	
    public void onClick (View v){
    	Intent intent = new Intent(SearchScreen.this, SelectCity.class);
    	startActivityForResult(intent, 1);
    }

    public String getAddress(double lat, double lng) {
        Geocoder g = new Geocoder(this,Locale.getDefault());
		

		Address address;
		String add="";
		Log.i("test", "beedu");
		try {

			List<Address> addresses = g.getFromLocation(lat, lng, 1);	
			if(addresses.size()>0)
			{
				
				address = addresses.get(0);

				for(int i=0;i<address.getMaxAddressLineIndex();i++)
				{
					add+=address.getAddressLine(i)+"\n";
				}
//				Toast.makeText(this, add, Toast.LENGTH_LONG).show();
			} 
			else{
				Toast.makeText(this, "we failed to locate the address", Toast.LENGTH_LONG).show();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
//			Toast.makeText(this, "i dnt knw", Toast.LENGTH_LONG);
		}
		return add;
	
    }
    
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
    	if (resultCode == Activity.RESULT_OK && requestCode==0){
    		Bundle bundle = data.getExtras();
        	String StoreName = bundle.getString("storename");
        	StoreText.setText(StoreName);
    	}
    	if (resultCode == Activity.RESULT_OK && requestCode==1){
    		Bundle bundle2 = data.getExtras();
        	String CityName = bundle2.getString("cityname");
        	CurLocation.setText(CityName);
    	}
    }

}